<template>
    <PageLayout 
        title="八字排盘" 
        show-back 
        @back="goBack" 
        fixed 
        shadow 
        :content-padding="false"
        :tabs="tabs"
        :scrollable="false"
        v-model="activeTab"
        @tab-change="handleTabChange"
    >
        <!-- 基本信息 tab -->
        <template #tab-basic>
            <div class="bazi-result">
                <div class="result-content">
                    <div class="placeholder-section">
                        <div class="placeholder-content">
                            <p class="placeholder-text">基本信息功能开发中...</p>
                        </div>
                    </div>
                </div>
            </div>
        </template>

        <!-- 基本排盘 tab -->
        <template #tab-bazi>
            <div class="bazi-result">
                <div class="result-content">
                    <!-- 基本信息 -->
                    <div class="info-section">
                        <!-- 隐私切换图标 - 右上角，位于修改图标左侧 -->
                        <van-icon
                            class="info-privacy-btn"
                            :name="isPrivacyMode ? 'closed-eye' : 'eye-o'"
                            @click="isPrivacyMode ? showInfo() : hideInfo()"
                            :aria-label="isPrivacyMode ? '显示' : '隐藏'"
                        />
                        <!-- 修改图标 - 右上角最右侧 -->
                        <van-icon
                            class="info-edit-btn"
                            name="edit"
                            @click="handleEdit"
                            aria-label="修改"
                        />
                        <div class="avatar_box">
                            <img :src="shengxiaoImage" class="avatar_img" alt="生肖">
                            <div class="avatar_right">
                                <div class="avatar_title">{{ displayName }}</div>
                                <div class="avatar_date">
                                    农历：{{ displayNongli }}
                                    <span v-if="resultData?.baseInfo?.genderTraditional" class="avatar_date_tips">
                                        {{ resultData?.baseInfo?.genderTraditional }}
                                    </span>
                                </div>
                                <div class="avatar_date">阳历：{{ displayYangli }}</div>
                            </div>
                        </div>
                    </div>

                <!-- 四柱八字展示 -->
                <BaziTable :bazi-data="baziPillars" />

                <!-- 智能干支图示按钮 -->
                <div v-if="resultData && relationPillars.length >= 4" class="relation-button-container">
                    <van-button 
                        type="primary" 
                        block 
                        round
                        class="relation-button"
                        @click="goToRelations"
                    >
                        智能干支图示
                    </van-button>
                </div>

                <!-- 原局关系提示 -->
                <YuanjuRelations :bazi-data="resultData" />

                <!-- 古籍查询区域 -->
                <AncientBooksQuery 
                    :bazi="buildBaziString" 
                    :zanggan="zangganArray"
                />
            
                </div>
            </div>
        </template>

        <!-- 专业细盘 tab -->
        <template #tab-detail>
            <div class="bazi-result">
                <div class="result-content">
                    <ProfessionalDetail
                        v-if="resultData"
                        :datetime="route.query.datetime as string || ''"
                        :gender="Number(resultData?.baseInfo?.gender) || 1"
                        :enable-zi-shi-support="resultData?.baseInfo?.enableZiShiSupport || false"
                        :bazi-data="fullBaziPillars"
                    />
                </div>
            </div>
            
           
        </template>

        <!-- 断事笔记 tab -->
        <template #tab-note>
            <div class="bazi-result">
                <div class="result-content">
                    <div class="placeholder-section">
                        <div class="placeholder-content">
                            <p class="placeholder-text">断事笔记功能开发中...</p>
                        </div>
                    </div>
                </div>
            </div>
        </template>
    </PageLayout>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast } from 'vant'
import { baziApi } from '@/api/bazi'
import PageLayout from '@/components/PageLayout.vue'
import AncientBooksQuery from '@/components/ancient-books/ancient_books_query.vue'
import YuanjuRelations from '@/components/YuanjuRelations.vue'
import ProfessionalDetail from '@/components/ProfessionalDetail.vue'
import BaziTable from '@/components/bazi_table.vue'
import { getTianganColor, getDizhiColor, getWuxingColor, getWuxing } from '@/utils/wuxing'

const router = useRouter()
const route = useRoute()
const resultData = ref<any>(null)
const loading = ref(false)
const activeTab = ref<string | number>('bazi')
const isPrivacyMode = ref(false) // 默认显示所有信息（睁眼状态）

// 定义四个选项卡
const tabs = [
    { label: '基本信息', value: 'basic' },
    { label: '基本排盘', value: 'bazi' },
    { label: '专业细盘', value: 'detail' },
    { label: '断事笔记', value: 'note' }
]

// 四柱名称映射
const pillarNames = {
    year: '年柱',
    month: '月柱',
    day: '日柱',
    hour: '时柱'
}

// 计算四柱数据（基本排盘）
const baziPillars = computed(() => {
    if (!resultData.value) return {}
    return {
        year: resultData.value.year,
        month: resultData.value.month,
        day: resultData.value.day,
        hour: resultData.value.hour
    }
})

// 计算完整数据（包含胎命身，用于专业细盘）
const fullBaziPillars = computed(() => {
    if (!resultData.value) return {}
    return {
        year: resultData.value.year,
        month: resultData.value.month,
        day: resultData.value.day,
        hour: resultData.value.hour,
        shengong: resultData.value.shengong,
        minggong: resultData.value.minggong,
        taiyuan: resultData.value.taiyuan
    }
})

// 构建关系组件所需的天干地支数据
const relationPillars = computed(() => {
    if (!resultData.value) return []
    const pillars = []
    
    // 获取地支十神（从藏干中获取第一个）
    const getZhiLabel = (zanggan: any[]): string => {
        if (!zanggan || zanggan.length === 0) return ''
        return zanggan[0]?.tenStar || ''
    }
    
    if (resultData.value.year?.stem && resultData.value.year?.branch) {
        pillars.push({
            gan: resultData.value.year.stem,
            zhi: resultData.value.year.branch,
            label: '年柱',
            zhiLabel: getZhiLabel(resultData.value.year?.zanggan),
            tenStar: resultData.value.year?.tenStar || ''
        })
    }
    
    if (resultData.value.month?.stem && resultData.value.month?.branch) {
        pillars.push({
            gan: resultData.value.month.stem,
            zhi: resultData.value.month.branch,
            label: '月柱',
            zhiLabel: getZhiLabel(resultData.value.month?.zanggan),
            tenStar: resultData.value.month?.tenStar || ''
        })
    }
    
    if (resultData.value.day?.stem && resultData.value.day?.branch) {
        pillars.push({
            gan: resultData.value.day.stem,
            zhi: resultData.value.day.branch,
            label: '日柱',
            zhiLabel: getZhiLabel(resultData.value.day?.zanggan),
            tenStar: resultData.value.day?.tenStar || ''
        })
    }
    
    if (resultData.value.hour?.stem && resultData.value.hour?.branch) {
        pillars.push({
            gan: resultData.value.hour.stem,
            zhi: resultData.value.hour.branch,
            label: '时柱',
            zhiLabel: getZhiLabel(resultData.value.hour?.zanggan),
            tenStar: resultData.value.hour?.tenStar || ''
        })
    }
    
    return pillars
})

// 返回上一页
const goBack = () => {
    router.back()
}

// 跳转到智能干支图示页面
const goToRelations = () => {
    // 从当前路由参数获取参数，传递给新页面
    const params = route.query
    router.push({
        path: '/bazi/relations',
        query: params
    })
}

// Tab 切换处理
const handleTabChange = (value: string | number) => {
    activeTab.value = value
}


// 获取天干颜色（使用工具类）
const getStemColor = (stem: string) => {
    return getTianganColor(stem)
}

// 获取地支颜色（使用工具类）
const getBranchColor = (branch: string) => {
    return getDizhiColor(branch)
}

// 获取干支颜色（用于干支组合显示）
const getGanZhiColor = (stem: string, branch: string) => {
    return {
        stem: getTianganColor(stem),
        branch: getDizhiColor(branch)
    }
}

// 生肖名称到图片索引的映射
const zodiacMap: Record<string, number> = {
    '鼠': 1,
    '牛': 2,
    '虎': 3,
    '兔': 4,
    '龙': 5,
    '蛇': 6,
    '马': 7,
    '羊': 8,
    '猴': 9,
    '鸡': 10,
    '狗': 11,
    '猪': 12
}

// 生肖图片路径映射
const shengxiaoImages: Record<number, string> = {
    1: new URL('../assets/shengxaio/sx_1.png', import.meta.url).href,
    2: new URL('../assets/shengxaio/sx_2.png', import.meta.url).href,
    3: new URL('../assets/shengxaio/sx_3.png', import.meta.url).href,
    4: new URL('../assets/shengxaio/sx_4.png', import.meta.url).href,
    5: new URL('../assets/shengxaio/sx_5.png', import.meta.url).href,
    6: new URL('../assets/shengxaio/sx_6.png', import.meta.url).href,
    7: new URL('../assets/shengxaio/sx_7.png', import.meta.url).href,
    8: new URL('../assets/shengxaio/sx_8.png', import.meta.url).href,
    9: new URL('../assets/shengxaio/sx_9.png', import.meta.url).href,
    10: new URL('../assets/shengxaio/sx_10.png', import.meta.url).href,
    11: new URL('../assets/shengxaio/sx_11.png', import.meta.url).href,
    12: new URL('../assets/shengxaio/sx_12.png', import.meta.url).href
}

// 获取生肖图片路径
const shengxiaoImage = computed(() => {
    const shengxiao = resultData.value?.baseInfo?.shengxiao
    if (!shengxiao) return ''
    const index = zodiacMap[shengxiao] || 1
    return shengxiaoImages[index] || shengxiaoImages[1]
})

// 隐藏敏感信息：用 *** 替换年月日、姓名
const displayName = computed(() => {
    if (!isPrivacyMode.value) {
        return resultData.value?.baseInfo?.name || '未填写'
    }
    return '***'
})

// 隐藏农历中的年月日
const displayNongli = computed(() => {
    const nongli = resultData.value?.baseInfo?.nongli || ''
    if (!isPrivacyMode.value || !nongli) {
        return nongli
    }
    // 替换农历中的年月日：格式如 "1989年九月十五 未时" -> "***年**月** **时"
    let result = nongli
        .replace(/\d+年/g, '***年') // 替换年份数字，如 "1989年" -> "***年"
        .replace(/[正二三四五六七八九十腊]+月/g, '**月') // 替换月份名称，如 "九月" -> "**月"
        .replace(/[初]+[一二三四五六七八九十\d]+/g, '**') // 替换"初X"，如 "初五" -> "**"
        .replace(/[子丑寅卯辰巳午未申酉戌亥]时/g, '**时') // 替换时辰，如 "未时" -> "**时"
    
    // 替换中文日期（在月份和时辰已替换后，匹配剩余的中文数字日期）
    // 匹配"**月"之后到"**时"之间的中文数字，或者空格前后的中文数字
    result = result.replace(/月\s*([一二三四五六七八九十]+)\s*/g, '月** ') // 匹配月份后的中文日期，如 "月 十五 " -> "月** "
    result = result.replace(/\s+([一二三四五六七八九十]+)\s+/g, ' ** ') // 替换中间的中文日期
    result = result.replace(/\s+([一二三四五六七八九十]+)(?=\*\*时)/g, ' **') // 替换"时"前的中文日期
    
    // 替换其他格式的日期
    result = result.replace(/\d+[日号]/g, '**') // 替换数字日期，如 "5日" -> "**"
    
    return result
})

// 隐藏阳历中的年月日
const displayYangli = computed(() => {
    const yangli = resultData.value?.baseInfo?.yangli || ''
    if (!isPrivacyMode.value || !yangli) {
        return yangli
    }
    // 替换阳历中的年月日：格式如 "1990年01月01日 00:00" -> "***年**月**日 **:**"
    return yangli
        .replace(/\d+年/g, '***年')
        .replace(/\d+月/g, '**月')
        .replace(/\d+日/g, '**日')
        .replace(/\d+:\d+/g, '**:***')
})

// 显示信息（睁眼）
const showInfo = () => {
    isPrivacyMode.value = false
}

// 隐藏信息（闭眼）
const hideInfo = () => {
    isPrivacyMode.value = true
}

// 修改功能（暂时提示正在开发中）
const handleEdit = () => {
    showToast({
        message: '正在开发中',
        duration: 2000
    })
}

// 获取排盘结果
const getBaziResult = async () => {
    loading.value = true
    try {
        // 从路由参数获取排盘参数
        const params = route.query
        if (params.datetime) {
            const response = await baziApi.getBaziInfo({
                datetime: params.datetime as string,
                gender: (parseInt(params.gender as string) || 1) as 0 | 1,
                name: params.name as string || '',
                longitude: params.longitude ? parseFloat(params.longitude as string) : undefined,
                latitude: params.latitude ? parseFloat(params.latitude as string) : undefined,
                enableZiShiSupport: params.enableZiShiSupport === 'true'
            })
            resultData.value = response.data
        } else {
            // 如果没有参数，尝试从localStorage获取
            const data = localStorage.getItem('baziResult')
            if (data) {
                resultData.value = JSON.parse(data)
            } else {
                router.push('/')
            }
        }
    } catch (error) {
        console.error('获取排盘结果失败:', error)
        router.push('/')
    } finally {
        loading.value = false
    }
}

// 构建八字字符串（年干年支月干月支日干日支时干时支）
const buildBaziString = computed(() => {
    if (!resultData.value) return ''
    const year = resultData.value.year
    const month = resultData.value.month
    const day = resultData.value.day
    const hour = resultData.value.hour
    
    if (!year?.stem || !year?.branch || !month?.stem || !month?.branch || 
        !day?.stem || !day?.branch || !hour?.stem || !hour?.branch) {
        return ''
    }
    
    return `${year.stem}${year.branch}${month.stem}${month.branch}${day.stem}${day.branch}${hour.stem}${hour.branch}`
})

// 计算藏干数组（用于调候用神组件）
const zangganArray = computed(() => {
    if (!resultData.value) return []
    
    return [
        resultData.value.year?.zanggan || [],
        resultData.value.month?.zanggan || [],
        resultData.value.day?.zanggan || [],
        resultData.value.hour?.zanggan || []
    ]
})

// 组件挂载时获取数据
onMounted(() => {
    getBaziResult()
})
</script>

<style scoped>
.bazi-result {
    width: 100%;
    max-width: 100%;
    height: 100%;
    min-height: 100%;
    background: #ffffff;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Helvetica Neue', Arial, sans-serif;
    padding-bottom: 20px;
    box-sizing: border-box;
    overflow-y: auto;
    overflow-x: hidden;
    position: relative;
}

.result-content {
    width: 100%;
    max-width: 100%;
    box-sizing: border-box;
    padding: 0;
    min-height: 100%;
    position: relative;
    overflow-x: hidden;
}



.section-title {
    font-size: 18px;
    font-weight: 600;
    color: #4d4d4d;
    margin: 0 0 16px 0;
    padding-bottom: 8px;
    border-bottom: 2px solid #3b82f6;
}

.info-section {
    padding: 12px;
    width: 100%;
    box-sizing: border-box;
    position: relative;
}

.avatar_box {
    display: flex;
    align-items: flex-start;
    gap: 16px;
    width: 100%;
}

.avatar_img {
    width: 60px;
    height: 60px;
    object-fit: contain;
    flex-shrink: 0;
    border-radius: 8px;
}

.avatar_right {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.avatar_title {
    font-size: 18px;
    color: #4d4d4d;
    font-weight: 600;
    line-height: 1.4;
}

.avatar_date {
    font-size: 15px;
    color: #4d4d4d;
    line-height: 1.5;
}

.avatar_date_tips {
    display: inline-block;
    margin-left: 8px;
    color: #4d4d4d;
    font-size: 14px;
    font-weight: 500;
}

.info-privacy-btn,
.info-edit-btn {
    position: absolute;
    top: 12px;
    font-size: 20px;
    color: #4d4d4d;
    cursor: pointer;
    z-index: 10;
    transition: all 0.2s ease;
}

.info-privacy-btn {
    right: 50px;
}

.info-edit-btn {
    right: 12px;
}

.info-privacy-btn:hover,
.info-edit-btn:hover {
    color: #4d4d4d;
}

.info-privacy-btn:active,
.info-edit-btn:active {
    transform: scale(0.95);
}




.gong-section {
    background: #ffffff;
    border-radius: 12px;
    padding: 16px;
    margin-bottom: 16px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    border: 1px solid #e2e8f0;
}

.gong-grid {
    display: grid;
    grid-template-columns: 1fr;
    gap: 20px;
}

.gong-item {
    background: #f8fafc;
    border-radius: 8px;
    padding: 16px;
    border: 1px solid #e2e8f0;
}

.gong-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding-bottom: 8px;
    border-bottom: 1px solid #e2e8f0;
}

.gong-name {
    font-size: 14px;
    color: #4d4d4d;
    font-weight: 600;
}

.gong-ganzhi {
    font-size: 18px;
    font-weight: 700;
    color: #4d4d4d;
    background: linear-gradient(135deg, #3b82f6, #1d4ed8);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
}

.gong-details {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 8px;
}

.detail-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 4px 0;
}

.wuxing-section {
    background: #ffffff;
    border-radius: 12px;
    padding: 16px;
    margin-bottom: 16px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    border: 1px solid #e2e8f0;
}

.wuxing-content {
    display: grid;
    grid-template-columns: 1fr;
    gap: 20px;
}

.wuxing-item {
    background: #f8fafc;
    border-radius: 8px;
    padding: 16px;
    border: 1px solid #e2e8f0;
}

.wuxing-title {
    font-size: 16px;
    color: #4d4d4d;
    font-weight: 600;
    margin: 0 0 16px 0;
}

.wuxing-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.wuxing-bar {
    display: flex;
    align-items: center;
    gap: 12px;
}

.wuxing-label {
    font-size: 14px;
    color: #4d4d4d;
    font-weight: 500;
    min-width: 20px;
}

.wuxing-progress {
    flex: 1;
    height: 8px;
    background: #e2e8f0;
    border-radius: 4px;
    overflow: hidden;
}

.wuxing-fill {
    height: 100%;
    background: linear-gradient(135deg, #3b82f6, #1d4ed8);
    border-radius: 4px;
    transition: width 0.3s ease;
}

.wuxing-value {
    font-size: 14px;
    color: #4d4d4d;
    font-weight: 600;
    min-width: 20px;
    text-align: center;
}

.wuxing-ss {
    font-size: 12px;
    color: #4d4d4d;
    min-width: 40px;
    text-align: center;
}

.other-section {
    background: #ffffff;
    border-radius: 12px;
    padding: 16px;
    margin-bottom: 16px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    border: 1px solid #e2e8f0;
}

.other-grid {
    display: grid;
    grid-template-columns: 1fr;
    gap: 20px;
}

.other-item {
    background: #f8fafc;
    border-radius: 8px;
    padding: 16px;
    border: 1px solid #e2e8f0;
}

.note-section {
    background: #ffffff;
    border-radius: 12px;
    padding: 16px;
    margin: 16px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    border: 1px solid #e2e8f0;
    min-height: 300px;
}

.note-content {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    min-height: 200px;
}

.note-placeholder {
    font-size: 14px;
    color: #4d4d4d;
    text-align: center;
}

.placeholder-section {
    background: #ffffff;
    border-radius: 12px;
    padding: 16px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    border: 1px solid #e2e8f0;
    min-height: 300px;
}

.placeholder-content {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    min-height: 200px;
}

.placeholder-text {
    font-size: 14px;
    color: #4d4d4d;
    text-align: center;
}


.relation-section-container {
    margin: 16px;
    padding: 0;
}

.relation-button-container {
    margin: 16px;
    padding: 0;
}

.relation-button {
    height: 44px;
    font-size: 16px;
    font-weight: 600;
}


.other-title {
    font-size: 16px;
    color: #4d4d4d;
    font-weight: 600;
    margin: 0 0 16px 0;
}

.jieqi-info,
.xingxiu-info {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.jieqi-item,
.xingxiu-item {
    display: flex;
    align-items: center;
    gap: 8px;
}

.jieqi-label,
.xingxiu-label {
    font-size: 12px;
    color: #4d4d4d;
    font-weight: 500;
    min-width: 60px;
}

.jieqi-value,
.xingxiu-value {
    font-size: 12px;
    color: #4d4d4d;
    font-weight: 500;
}

</style>